package zhihui.mobile.ui.shop;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.IconHintView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zgm.utils.DateUtils;
import com.zgm.utils.DensityUtil;
import com.zgm.utils.UiUtils;
import com.zgm.utils.ui.UiSearchHeader;

import java.util.List;

import zhihui.mobile.R;
import zhihui.mobile.bean.shop.BannerInfo;
import zhihui.mobile.bean.shop.SpuInfo;
import zhihui.mobile.bean.shop.sales.SalesDesc;
import zhihui.mobile.bean.shop.sales.SalesInfo;
import zhihui.mobile.bean.shop.sales.SalesShopInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.presenter.IPresenter;
import zhihui.mobile.presenter.shop.ShopMainPresenter;
import zhihui.mobile.ui.BaseActivity;
import zhihui.mobile.ui.main.MainActivity;
import zhihui.mobile.ui.shop.list.ShopListActivity;
import zhihui.mobile.ui.shop.web.ShopWebActivity;
import zhihui.mobile.ui.utils.ShopItemUtils;
import zhihui.mobile.ui.utils.UiFooterLayout;

/**
 * Created by 张公铭 on 2017/7/19 0019.
 */

public class ShopMainActivity extends BaseActivity implements IShopMainContract.IShopMainView
{
    private ShopMainPresenter shopMainPresenter = new ShopMainPresenter();

    private UiSearchHeader mHeader;
    private PullToRefreshScrollView ps_content;
    private RollPagerView pv_banner;
    private LinearLayout ly_sales_root;
    private LinearLayout ly_sales;
    private LinearLayout ly_time_root;
    private TextView tv_sales_desc;
    private LinearLayout ly_time;
    private TextView tv_time_desc;
    private ImageView iv_group;
    private ImageView iv_fresh;
    private ImageView iv_milk;
    private ImageView iv_wine;
    private ImageView iv_clean;
    private LinearLayout ly_topic;
    private LinearLayout ly_topic_content;
    private LinearLayout ly_recommend_root;
    private LinearLayout ly_recommend;
    private UiFooterLayout mFooter;
    private ImageView iv_all_category;
    private BannerAdapter bannerAdapter;

    private boolean headerChange = false;

    @Override
    public void initView()
    {
        mHeader = (UiSearchHeader) findViewById(R.id.shop_main_header);
        mHeader.setEditTextBackgroudTrans();
        mHeader.setRightOneButtonIcon(R.drawable.wrait_cart);
        mHeader.setEdittextHind("搜索");
        mHeader.hindLeftButton();
        mHeader.hindRightButtonTwo();
        mHeader.setRightButtonOneOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shopMainPresenter.goShopCart(ShopMainActivity.this, ShopMainActivity.this);
            }
        });
        mHeader.setListener(new UiSearchHeader.IOnSearchListener()
        {
            @Override
            public void searchText(String text)
            {
                shopMainPresenter.search(text);
            }
        });

        //判断当前设备版本号是否为4.4以上，如果是，则通过调用setTranslucentStatus让状态栏变透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            setTranslucentStatus(true);
            mHeader.showBarView(UiUtils.getStatusBarHeight(this));
        }

        ps_content = (PullToRefreshScrollView) findViewById(R.id.sl_shop_main_content);
        ps_content.setOnScrollChangedListener(new PullToRefreshScrollView.IOnScrollChangedListener()
        {
            @Override
            public void onScrollChanged(ScrollView scrollView, int x, int y, int oldx, int oldy)
            {
                int maxHeight = DensityUtil.dip2px(ShopMainActivity.this, 70);
                if (y > maxHeight && !headerChange)
                {
                    mHeader.setEditTextBackgroud();
                    headerChange = true;
                }

                if(y < maxHeight && headerChange)
                {
                    mHeader.setEditTextBackgroudTrans();
                    headerChange = false;
                }
            }
        });

        ps_content.setMode(PullToRefreshBase.Mode.BOTH);
        ps_content.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>()
        {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView)
            {
                shopMainPresenter.initView();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView)
            {
                shopMainPresenter.refreshRecommend();
            }
        });

        //获取屏幕宽度
        WindowManager m = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        m.getDefaultDisplay().getMetrics(outMetrics);

        //计算宽高，我需要的图片尺寸是750*340
        double width = outMetrics.widthPixels; //乘以2是因为左右两侧的宽度
        double c = width / 750;
        double height = 340 * c; //750*340

        pv_banner = (RollPagerView) findViewById(R.id.pv_show_main_banner);
        ViewGroup.LayoutParams layoutParams = pv_banner.getLayoutParams();
        layoutParams.width = (int) width;
        layoutParams.height = (int) height;
        pv_banner.setLayoutParams(layoutParams);
        //设置每个图片的切换时间
        pv_banner.setPlayDelay(3000);
        //设置图片切换动画时间
        pv_banner.setAnimationDurtion(500);
        pv_banner.setHintView(new IconHintView(this, R.drawable.tips_select, R.drawable.tips_normal, 20));
        bannerAdapter = new BannerAdapter(this);
        pv_banner.setAdapter(bannerAdapter);
        pv_banner.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(int position)
            {
                goWeb(bannerAdapter.getItem(position).getUrl());
            }
        });

        //抢购
        ly_sales_root = (LinearLayout) findViewById(R.id.ly_shop_main_qg_sales);
        ly_sales_root.setVisibility(View.GONE);
        ly_sales_root.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shopMainPresenter.goSalesActivity(1);
            }
        });
        ly_sales = (LinearLayout) findViewById(R.id.ly_shop_main_sale);
        ly_sales.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shopMainPresenter.goSalesActivity(1);
            }
        });

        tv_sales_desc = (TextView) findViewById(R.id.iv_shop_main_purchase_desc);

        //秒杀
        ly_time_root = (LinearLayout) findViewById(R.id.ly_shop_main_ms_sales);
        ly_time_root.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shopMainPresenter.goSalesActivity(2);
            }
        });
        ly_time_root.setVisibility(View.GONE);
        ly_time = (LinearLayout) findViewById(R.id.ly_shop_main_time_content);
        ly_time.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shopMainPresenter.goSalesActivity(2);
            }
        });

        tv_time_desc = (TextView) findViewById(R.id.iv_shop_main_time_desc);

        iv_group = (ImageView) findViewById(R.id.iv_shop_main_group);
        iv_group.setVisibility(View.GONE);

        ly_topic = (LinearLayout) findViewById(R.id.ly_shop_main_topic);
        ly_topic.setVisibility(View.GONE);

        ly_topic_content = (LinearLayout) findViewById(R.id.ly_shop_main_topic_content);

        ly_recommend_root = (LinearLayout) findViewById(R.id.ly_shop_main_recommend_root);
        ly_recommend_root.setVisibility(View.GONE);
        ly_recommend = (LinearLayout) findViewById(R.id.ly_shop_main_recommend);

        iv_fresh = (ImageView) findViewById(R.id.iv_shop_main_icon_fresh);
        iv_fresh.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shopMainPresenter.goShopListByCategory("555");
            }
        });

        iv_milk = (ImageView) findViewById(R.id.iv_shop_main_icon_oil);
        iv_milk.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shopMainPresenter.goShopListByCategory("666");
            }
        });

        iv_wine = (ImageView) findViewById(R.id.iv_shop_main_icon_household);
        iv_wine.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shopMainPresenter.goShopListByCategory("777");
            }
        });

        iv_clean = (ImageView) findViewById(R.id.iv_shop_main_icon_all);
        iv_clean.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shopMainPresenter.goShopListByCategory("888");
            }
        });
        mFooter = (UiFooterLayout) findViewById(R.id.footer_shop_main);
        mFooter.change(UiFooterLayout.Meun.Shop);
        shopMainPresenter.initView();
    }


    @TargetApi(19)
    private void setTranslucentStatus(boolean on)
    {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on)
        {
            winParams.flags |= bits;
        } else
        {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    protected int getLayoutResId()
    {
        return R.layout.shop_main_activity;
    }

    @Override
    protected IPresenter[] getPresenters()
    {
        return new IPresenter[]{shopMainPresenter};
    }

    @Override
    protected void onInitPresenter()
    {
        shopMainPresenter.init(this, this);
    }

    @Override
    public void searchRequestFocus()
    {
        mHeader.editeRequestFocus();
        mHeader.bringToFront();
        mFooter.bringToFront();
    }

    @Override
    public void updateBanner(List<BannerInfo> list)
    {
        bannerAdapter.setmList(list);
        bannerAdapter.notifyDataSetChanged();
    }

    @Override
    public void updateQgSales(SalesInfo salesInfo)
    {
        if (salesInfo == null)
        {
            ly_sales_root.setVisibility(View.GONE);
            return;
        }
        List<SalesShopInfo> list = salesInfo.getSkus();
        if (list == null || list.size() == 0)
        {
            return;
        }

        SalesDesc salesDesc = salesInfo.getSalemsg();
        //判断系统时间是否在活动范围之内
        long startTime = salesDesc.getStarttime();
        if (!DateUtils.isBefor(startTime))
        {
            tv_sales_desc.setText(DateUtils.getHour(startTime) + " 场正在进行中");
        } else
        {
            tv_sales_desc.setText(DateUtils.getHour(startTime) + " 场即将开始");
        }
        ly_sales_root.setVisibility(View.VISIBLE);
        ly_sales.removeAllViews();
        createdSalesView(list, salesDesc.getId(), ly_sales);
    }

    @Override
    public void updateMsSales(SalesInfo salesInfo)
    {
        if (salesInfo == null)
        {
            ly_time_root.setVisibility(View.GONE);
            return;
        }

        List<SalesShopInfo> list = salesInfo.getSkus();
        if (list == null || list.size() == 0)
        {
            return;
        }
        SalesDesc salesDesc = salesInfo.getSalemsg();
        //判断系统时间是否在活动范围之内
        long startTime = salesDesc.getStarttime();
        if (!DateUtils.isBefor(startTime))
        {
            tv_time_desc.setText(DateUtils.getHour(startTime) + " 场正在进行中");
        } else
        {
            tv_time_desc.setText(DateUtils.getHour(startTime) + " 场即将开始");
        }
        ly_time_root.setVisibility(View.VISIBLE);
        ly_time.removeAllViews();
        createdSalesView(list, salesDesc.getId(), ly_time);
    }

    private void createdSalesView(List<SalesShopInfo> list, final int salesId, ViewGroup root)
    {
        for (int i = 0; i < list.size(); i++)
        {
            final SalesShopInfo shopInfo = list.get(i);
            if (shopInfo == null)
            {
                continue;
            }
            View view = LayoutInflater.from(this).inflate(R.layout.shop_item, ly_sales, false);
            ImageView imageView = (ImageView) view.findViewById(R.id.iv_shop_sale_item_icon);
            ImageLoader.getInstance().displayImage(Config.FILE_URL + shopInfo.getThumbnail(), imageView);
            TextView tv_price = (TextView) view.findViewById(R.id.tv_shop_sale_item_price);
            tv_price.setText("￥" + ((double) shopInfo.getAmount() / 100));
            TextView tv_originalprice = (TextView) view.findViewById(R.id.tv_shop_sale_item_originalprice);
            tv_originalprice.setText("￥" + ((double) shopInfo.getMoney() / 100));
            tv_originalprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            root.addView(view);
        }
    }

    @Override
    public void updateGroup(final List<BannerInfo> list)
    {
        if (list == null || list.size() == 0)
        {
            return;
        }
        iv_group.setVisibility(View.VISIBLE);
        ImageLoader.getInstance().displayImage(Config.FILE_URL + list.get(0).getUrl(), iv_group);
        iv_group.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                goWeb(list.get(0).getUrl());
            }
        });
    }

    @Override
    public void updateTopic(List<BannerInfo> list)
    {
        if (list == null || list.size() == 0)
        {
            return;
        }
        ly_topic.setVisibility(View.VISIBLE);
        ly_topic_content.removeAllViews();
        for (int i = 0; i < list.size(); i++)
        {
            final BannerInfo bannerInfo = list.get(i);
            ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DensityUtil.dip2px(this, 210));
            layoutParams.setMargins(0, DensityUtil.dip2px(this, 5), 0, 0);
            imageView.setLayoutParams(layoutParams);
            imageView.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    goWeb(bannerInfo.getUrl());
                }
            });
            ImageLoader.getInstance().displayImage(list.get(i).getUrl(), imageView);
            ly_topic_content.addView(imageView);
        }
    }

    @Override
    public void updateRecommend(List<SpuInfo> list)
    {
        if (list == null || list.size() == 0)
        {
            return;
        }
        ly_recommend_root.setVisibility(View.VISIBLE);
        ShopItemUtils.createdItem(this, list, ly_recommend, new ShopItemUtils.IItemOnClickListener()
        {
            @Override
            public void goShopDetails(int shopId, int salesId)
            {
                shopMainPresenter.goShopDetails(ShopMainActivity.this, shopId, salesId, ShopMainActivity.this);
            }
        });
    }

    @Override
    public void clearRecommend()
    {
        ly_recommend.removeAllViews();
    }


    @Override
    public void refreshComplete()
    {
        ps_content.onRefreshComplete();
    }

    @Override
    public void goShopListActivity(int type)
    {
        Intent intent = new Intent(this, ShopListActivity.class);
        intent.putExtra("dataType", type);
        startActivity(intent);
    }

    @Override
    public void updateCartNum(int num)
    {
        mHeader.setRightButtonOneNum(num);
    }

    private void goWeb(String url)
    {
        Intent intent = new Intent(ShopMainActivity.this, ShopWebActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }
}
